
package webshop.web;

import java.io.IOException;
import java.io.PrintWriter;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import webshop.data.Person;

/**
 * Finds a person in the database based on text input.
 * @author Ohm & Zim.
 */
public class PersonFindServlet extends AbstractSuperServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        EntityManager em = emf.createEntityManager();
        PrintWriter out = response.getWriter();

        // Gets the input.
        String name = request.getParameter("name");

        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache");
        response.setHeader("Expires", "0");

        out.println("<html><head><title>" + this.getClass().getName() + "</title></head><body>");
        out.println("<h1>Person Finder</h1>");

        out.println("<table>");
        out.println("<tr><th>Person</th></tr>");

        // Finds the person based on the given input.
        PersonUtil personUtil= new PersonUtil(em);
        Person person = personUtil.findPerson(name);

        if (person != null) {
            out.println("<tr><td>" + person.getPersonId() + "</td><td>" +
                    person.getName() + "</td><td>" +
                    person.getAddress() + "</td><td>" +
                    person.getPhone() + "</td></tr>");
        }

        out.println("</table>");

        out.println("<hr/>");
        out.println("<p><a href=\"index.html\">Home</a></p>");
        out.println("<p><a href=adminPage.html>Back to admin page</a></p>");

        out.println("</body>");
        out.println("</html>");


        em.close();
        out.close();
    }
}
